package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;

import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据:{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 分页查询订单
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R page(int page, int pageSize) {
        //构造分页构造器对象
        IPage<Orders> ordersIPage = new Page(page, pageSize);
        IPage<OrdersDto> ordersDtoIPage=new Page<>();
        //构建查询条件构造器
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        //添加排序条件
        qw.orderByDesc(Orders::getOrderTime);
        //执行分页条件查询  分类id到分类名称
        orderService.page(ordersIPage, qw);

        List<Orders> records = ordersIPage.getRecords();
        //创建一个OrdersDto集合
        ArrayList<OrdersDto> ordersDtos = new ArrayList<>();
        //遍历records
        for (Orders record : records){
            //创建OrdersDto对象
            OrdersDto ordersDto = new OrdersDto();
            //将record拷贝到ordersDto中
            BeanUtil.copyProperties(record,ordersDto);
            //获取到每一个订单的id
            Long orderId = record.getId();
            //条件构造器
            LambdaQueryWrapper<OrderDetail> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderDetail::getOrderId,orderId);
            List<OrderDetail> list1 = orderDetailService.list(queryWrapper);
            ordersDto.setOrderDetails(list1);
            ordersDtos.add(ordersDto);
        }
        ordersDtoIPage.setRecords(ordersDtos);
        return R.success(ordersDtoIPage);
    }
}
